var port = (process.env.VMC_APP_PORT || 3000);
var host = (process.env.VCAP_APP_HOST || 'localhost');
var http = require('http');

var MIME_TYPES = {  
  
    '.txt': 'text/plain',  
    '.md': 'text/plain',  
    '': 'text/plain',  
    '.html': 'text/html',  
    '.css': 'text/css',  
    '.js': 'application/javascript',  
    '.json': 'application/json',  
    '.jpg': 'image/jpeg',  
    '.png': 'image/png',  
    '.gif': 'image/gif'  
  
};

var path = require('path');  
var fs = require('fs');  
var url = require('url');

http.createServer(function (request, response) {
    var pathname = url.parse(request.url).pathname;
    pathname = pathname === '/' ? "/index.html":pathname;
    var realPath = "xmap" + pathname;
    path.exists(realPath, function (exists) {
        if (!exists) {
            response.writeHead(404, {
                'Content-Type': 'text/plain'
            });
 
            response.write("This request URL " + pathname + " was not found on this server.");
            response.end();
        } else {
            fs.readFile(realPath, "binary", function (err, file) {
                if (err) {
                    response.writeHead(500, {
                        'Content-Type': 'text/plain'
                    });
 
                    response.end(err);
                } else {
                  var ext = path.extname(realPath);
                   var contentType = MIME_TYPES[ext] || "text/plain";
                    response.writeHead(200, {
                        'Content-Type': contentType
                    });
 
                    response.write(file, "binary");
 
                    response.end();
                }
            });
        }
    });
  
}).listen(port, host);


